package com.ljx.recruitment.sale.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.ljx.recruitment.common.constant.CacheConstants;
import com.ljx.recruitment.common.exception.ApiException;
import com.ljx.recruitment.common.util.RedisUtil;
import com.ljx.recruitment.sale.constant.SaleConstant;
import com.ljx.recruitment.sale.domain.vo.req.SmsSendReq;
import com.ljx.recruitment.sale.domain.vo.req.SmsVerifyReq;
import com.ljx.recruitment.sale.domain.vo.resp.SmsSendResp;
import com.ljx.recruitment.sale.enums.SmsTypeEnum;
import com.ljx.recruitment.sale.service.SmsService;
import com.ljx.recruitment.sale.service.SmsStrategy;
import com.ljx.recruitment.sale.service.impl.sms.TrialApplicationSmsStrategy;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @Author: LiJunXi
 * @Description:
 * @Date: 2025-02-15  14:56
 */
@Service
public class SmsServiceImpl implements SmsService {

    @Value("${spring.profiles.active}")
    private String profilesActive;

    @Override
    public SmsSendResp sendSms(SmsSendReq req) {
        SmsStrategy smsStrategy = getSmsStrategy(req.getType());
        String key = RandomUtil.randomString(10);
        String code = smsStrategy.send(req.getPhone());
        RedisUtil.set(CacheConstants.getKey(CacheConstants.SMS, key), code, CacheConstants.SMS_EXPIRE_TIME);
        SmsSendResp resp = new SmsSendResp(key);
        if (SaleConstant.DEV.equals(profilesActive)) {
            resp.setCode(code);
        }
        return resp;
    }

    private SmsStrategy getSmsStrategy(Integer type) {
        if (type.equals(SmsTypeEnum.TRIAL_APPLICATION.getKey())) {
            return SpringUtil.getBean(TrialApplicationSmsStrategy.class);
        } else {
            throw new ApiException("短信类型不存在");
        }
    }

    @Override
    public boolean verify(SmsVerifyReq req) {
        SmsStrategy smsStrategy = getSmsStrategy(req.getType());
        return smsStrategy.verify(req.getKey(), req.getCode());
    }
}
